<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="供应商名称">
              <el-select filterable @change="onSearch(1)" v-model="formSearch.supplier_id" placeholder="选择供应商" clearable
                class="form-width">
                <el-option v-for="item in supplierOptions" :key="item.Id" :label="item.supplier_name" :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合同编号">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.contract_num"
                placeholder="输入合同编号"></el-input>
            </el-form-item>
            <el-form-item label="合同名称">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.contract_name"
                placeholder="输入合同名称"></el-input>
            </el-form-item>
            <el-form-item label="合同状态">
              <el-select filterable @change="onSearch(1)" v-model="formSearch.contract_status" placeholder="选择合同状态"
                clearable class="form-width">
                <el-option label="待生效" :value="1"></el-option>
                <el-option label="已生效" :value="2"></el-option>
                <el-option label="已失效" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="合同签约日期">
                <el-date-picker @change="onSearch(1)" clearable value-format="yyyy-MM-dd" class="form-width"
                  v-model="formSearch.signiDate" type="daterange" range-separator="-" start-placeholder="开始日期"
                  end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="合同生效日期">
                <el-date-picker @change="onSearch(1)" clearable value-format="yyyy-MM-dd" class="form-width"
                  v-model="formSearch.StartDate" type="daterange" range-separator="-" start-placeholder="开始日期"
                  end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="合同失效日期">
                <el-date-picker @change="onSearch(1)" clearable value-format="yyyy-MM-dd" class="form-width"
                  v-model="formSearch.endDate" type="daterange" range-separator="-" start-placeholder="开始日期"
                  end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker @change="onSearch(1)" clearable value-format="yyyy-MM-dd" class="form-width"
                  v-model="formSearch.startTime" type="daterange" range-separator="-" start-placeholder="开始日期"
                  end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="创建人">
                <el-select filterable @change="onSearch(1)" v-model="formSearch.user_id" placeholder="选择创建人" clearable
                  class="form-width">
                  <el-option v-for="item in qyUserList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button type="primary" @click="addFunc"
            v-if="$isPer(permission, ['purchaseContract_add'])">新增采购合同</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['purchase_deleteContract'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
            v-if="$isPer(permission, ['purchase_updateContract'])">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table border ref="table" @row-click="handleHighlightChangeTable" highlight-selection-row :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData"
          @selection-change="handleSelectionChange" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_gysmc')" min-width="180px" prop="supplier_name" label="供应商名称"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_htbh')" min-width="130px" prop="contract_num" label="合同编号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_htmc')" min-width="180px" prop="contract_name" label="合同名称"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.contract_name || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_htzt')" min-width="100px" prop="contract_status" label="合同状态"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.contract_status == 1">待生效</span>
              <span v-if="scope.row.contract_status == 2">已生效</span>
              <span v-if="scope.row.contract_status == 3">已失效</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_htqyrq')" min-width="120px" prop="signing_date" label="合同签约日期"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.signing_date || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_htsxrq')" min-width="120px" prop="effective_date" label="合同生效日期"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.effective_date || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_htsxrq2')" min-width="120px" prop="expiring_date" label="合同失效日期"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.expiring_date || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_cjsj')" min-width="180px" prop="created_at" label="创建时间"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.created_at || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('cght_cjr')" min-width="120px" prop="name" label="创建人"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.name || '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import purchaseApi from "@/api/purchaseApi";
import adminApi from "@/api/adminApi";
export default {
  name: "purchaseContractManagement",
  components: {},
  data() {
    return {
      tableLoading: false,
      userInfo: "",
      tableData: [1],
      formSearch: {},
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],//多选列表
      supplierOptions: [],//供应商列表
      qyUserList: [],//企业人员
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();
    this.getContract();//采购合同列表
    this.getSupplier();//供应商列表
    this.getAdminList();//企业人员
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    getAdminList() {
      adminApi.getAdminList({
        identity: 1,
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, '企业人员')
        if (res.code == 200) {
          this.qyUserList = res.data.list;
        }
      })
    },
    // -----------------------供应商列表--------------------------
    getSupplier() {
      purchaseApi.getSupplier({
        page: 1,
        num: 999,
        interact_status: 1
      }).then(res => {
        console.log(res, "供应商列表")
        if (res.code == 200) {
          this.supplierOptions = res.data.list;
        }
      })
    },
    // -----------------------采购合同列表-----------------------------
    getContract() {
      this.tableLoading = true;
      let formSearch = this.formSearch;
      console.log(formSearch, "参数")
      purchaseApi.getContract({
        page: this.page,
        num: this.num,
        contract_num: formSearch.contract_num || '',
        contract_name: formSearch.contract_name || '',
        contract_status: formSearch.contract_status || '',
        user_id: formSearch.user_id || '',
        supplier_id: formSearch.supplier_id || '',
        // 签约时间
        signing_date_start: formSearch.signiDate ? formSearch.signiDate[0] : '',
        signing_date_end: formSearch.signiDate ? formSearch.signiDate[1] : '',
        // 生效时间
        effective_date_start: formSearch.StartDate ? formSearch.StartDate[0] : '',
        effective_date_end: formSearch.StartDate ? formSearch.StartDate[1] : '',
        // 失效时间
        expiring_date_start: formSearch.endDate ? formSearch.endDate[0] : '',
        expiring_date_end: formSearch.endDate ? formSearch.endDate[1] : '',
        // 创建时间
        start_time: formSearch.startTime ? formSearch.startTime[0] : '',
        end_time: formSearch.startTime ? formSearch.startTime[1] : '',
      }).then(res => {
        console.log(res, "采购合同列表")
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // -----------------------编辑按钮-----------------------------
    editFunc() {
      let multipleSelection = this.multipleSelection;
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/addPurchaseContractPage',
        query: {
          id: multipleSelection[0].Id,
          route_title: '编辑采购合同'
        }
      })
    },
    // -----------------------删除按钮-----------------------------
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let delete_arr = [];
      multipleSelection.forEach(item => {
        delete_arr.push(item.Id);
      })
      this.$confirm('此操作将删除已勾选合同, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteContract({ delete_arr });
      }).catch(() => {
      });
    },
    deleteContract(obj) {
      purchaseApi.deleteContract(obj).then(res => {
        console.log(res, "删除合同")
        if (res.code == 200) {
          this.onSearch();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // ----------------------------table点击行-选中----------------------------
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      page = typeof page == 'number' ? page : this.page;
      this.page = page;
      this.getContract();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    addFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/addPurchaseContractPage'
      })
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>